<template>
  <div class="table-app-container">
    <div class="fixed-table" style="border: 0;">
      <div class="fixed-table-actionbar">
        <div class="action-bar">
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="onAddTag">添加标签</el-button>
        </div>
      </div>
      <PageableTable
        :loading="loading"
        :data="insideTableData"
        :total="0"
        :table-height="tableHeight"
        :disable-pageable="true"
        class="fixed-table-table"
      >
        <el-table-column v-for="column in insideColumns" :key="column.key" :width="column.width" :label="column.title" :prop="column.key" :sortable="column.sortable">
          <template slot-scope="scope">
            <column-render :render="column.render" :row="scope.row" :column="column" />
          </template>
        </el-table-column>
        <el-table-column label="属性">
          <template slot-scope="scope">
            <el-tag v-for="attr in scope.row.attrs" :key="attr.field" type="info" style="margin-right: 3px;">{{ attr.name }} : {{ attr.field }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="!forSelection" label="操作" align="center" width="120" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button title="编辑" type="text" size="mini" icon="el-icon-edit" @click="onEditTag(row)" />
            <el-button title="删除" type="text" size="mini" icon="el-icon-delete" @click="remove(row._id)" />
            <el-button title="属性" type="text" size="mini" icon="el-icon-s-operation" @click="onEditAttr(row)" />
          </template>
        </el-table-column>
      </PageableTable>
    </div>
    <FormDialog title="标签维护" :show.sync="addTagDialogVisible" width="30%" :drawer="false" @on-ok="onAddTagOk" @on-cancel="onAddTagCancel">
      <el-form v-if="addTagDialogVisible" ref="addform" :model="addFormItem" :rules="rules" label-width="100px" size="mini">
        <input v-model="addFormItem._id" type="hidden">
        <el-form-item label="名称" prop="name" required>
          <el-input v-model="addFormItem.name" />
        </el-form-item>
        <el-form-item label="标识符" prop="code" required>
          <el-input v-model="addFormItem.code" />
        </el-form-item>
      </el-form>
    </FormDialog>
    <FormDialog title="属性维护" :show.sync="addTagAttrDialogVisible" width="20%" :drawer="true" @on-ok="onAddTagAttrOk" @on-cancel="onAddTagAttrCancel">
      <el-form v-if="addTagAttrDialogVisible" ref="addAttrform" :model="addAttrFormItem" label-width="100px" size="mini">
        <el-form-item v-for="attr in allAttrs" :key="attr.field" :label="attr.name" :prop="attr.field">
          <el-switch v-model="addAttrFormItem[attr.field]" />
        </el-form-item>
      </el-form>
    </FormDialog>
  </div>
</template>

<script>
import FormDialog from '@neu/biz-core/components/FormDialog'
import PageableTable from '@neu/biz-core/components/PageableTable'
import { update, create, remove, addAttrs } from '@neu/cmdb-ui/api/tag'
import { getTags } from '@neu/cmdb-ui/api/schema'
import databind from '@neu/biz-core/mixins/databind'
import { deepClone, debounce } from '@neu/biz-core/utils'
import { on } from '@neu/biz-core/utils/utils'

const addFormItem = {
  code: '',
  name: '',
  schemadef: ''
}

const rules = {
  code: [
    { required: true, message: '标识符必填项', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '标签名称必填项', trigger: 'blur' }
  ]
}

export default {
  name: 'TagsPage',
  components: {
    FormDialog,
    PageableTable
  },
  mixins: [databind],
  props: {
    schemadef: {
      required: true,
      type: String
    }
  },
  data() {
    return {
      r: getTags(this.schemadef),
      d: remove,
      insideColumns: [
        { title: '标签名', key: 'name', width: 150 },
        { title: '标签标识', key: 'code', width: 150 }
      ],
      originData: {},
      addTagDialogVisible: false,
      addFormItem: { ...addFormItem, schemadef: this.schemadef },
      rules: { ...rules },
      addTagAttrDialogVisible: false,
      addAttrFormItem: {},
      allAttrs: []
    }
  },
  methods: {

    // 预处理API返回的数据
    responseFormatter(result) {
      this.originData = Object.freeze(deepClone(result))
      result = result.map(it => {
        const { _id, name, code } = it
        const allAttrs = [...it.category.attrs, ...it.schemadef.attrs]
        this.allAttrs = allAttrs
        const attrs = it.attrs.map(a => {
          const b = allAttrs.find(b => b.field === a)
          if (b) {
            return {
              field: b.field,
              name: b.name
            }
          }
        })

        return {
          _id,
          name,
          code,
          attrs
        }
      })
      return result
    },

    // 打开标签表单
    onAddTag() {
      this.addTagDialogVisible = true
    },

    // 打开编辑标签表单
    onEditTag(row) {
      this.addFormItem = { _id: row._id, name: row.name, code: row.code, schemadef: this.schemadef }
      // 打开对话框
      this.addTagDialogVisible = true
    },

    // 提交表单
    onAddTagOk() {
      const that = this
      this.$refs.addform.validate(valid => {
        if (!valid) return
        if (that.addFormItem._id) {
          update(this.addFormItem._id, this.addFormItem).then(cb)
        } else {
          create(this.addFormItem).then(cb)
        }

        function cb() {
          that.$message({
            showClose: true,
            message: '操作成功！',
            type: 'success'
          })
          that.$refs.addform.resetFields()
          that.refresh()
          that.addTagDialogVisible = false
        }
      })
    },

    // 取消表单
    onAddTagCancel() {
      this.$refs.addform.resetFields()
      this.addTagDialogVisible = false
    },

    // 打开属性维护表单
    onEditAttr(row) {
      this.editTagId = row._id
      row.attrs.forEach(it => {
        this.addAttrFormItem[it.field] = true
      })
      this.addTagAttrDialogVisible = true
    },

    // 提交属性维护表单
    onAddTagAttrOk() {
      const attrs = Object.entries(this.addAttrFormItem).filter(item => !!item[1]).map(item => item[0])
      addAttrs(this.editTagId, { attrs }).then(response => {
        this.addAttrFormItem = {}
        this.refresh()
        this.addTagAttrDialogVisible = false
      })
    },

    // 取消属性维护表单
    onAddTagAttrCancel() {
      this.addAttrFormItem = {}
      this.addTagAttrDialogVisible = false
    },

    // 自适应页面高度
    initListener() {
      this.$_resizeHandler = debounce(() => {
        const _this = this
        // 页面头高度 50
        // .app-container padding上下总和 16
        // document.querySelector('.table-app-container .fixed-table-filter').offsetHeight
        // document.querySelector('.table-app-container .fixed-table-actionbar')
        // 翻页组件高度 42
        // .fixed-table padding上下和边框 18
        const baseInfoSel = document.querySelector('.app-container .schema-edit-container .base-info')
        const baseInfoHeight = baseInfoSel ? baseInfoSel.offsetHeight : 0

        const tabsSel = document.querySelector('.el-tabs__header')
        const tabsHeight = tabsSel ? tabsSel.offsetHeight + 15 : 0

        const tableFilterSel = document.querySelector('.table-app-container .fixed-table-filter')
        const tableFilterHeight = tableFilterSel ? tableFilterSel.offsetHeight : 0

        const tableActionbarSel = document.querySelector('.table-app-container .fixed-table-actionbar')
        const tableActionbarHeight = tableActionbarSel ? tableActionbarSel.offsetHeight : 0

        const assetTableBarSel = document.querySelector('.table-app-container .asset-table-bar')
        const assetTableBarHeight = assetTableBarSel ? assetTableBarSel.offsetHeight : 0

        const filterTreeSel = document.querySelector('.table-app-container .filter-tree')
        if (filterTreeSel) {
          filterTreeSel.style.height = (window.innerHeight - 50 - 16) + 'px'
        }

        _this.tableHeight = window.innerHeight - 50 - 16 - baseInfoHeight - tabsHeight - tableFilterHeight - assetTableBarHeight - tableActionbarHeight - 22
      }, 300)

      on(window, 'resize', this.$_resizeHandler)
    }
  }
}
</script>
